package com.zwd.deep.service;

import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zwd
 */
@Service
@Slf4j
public class MinioService {
    public static int TYPE_TASK = 1;
    public static int TYPE_AVATAR = 2;

    private static final String TASK = "task";
    private static final String AVATAR = "avatar";

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    public String uploadFile(MultipartFile file, int typeInteger){
        // 获取图片文件名
        String originalFilename = file.getOriginalFilename();

        // 检查文件名是否合法（可选）
        if (originalFilename == null || !originalFilename.matches(".*\\.(jpg|jpeg|png|gif|bmp)$")) {
            throw new RuntimeException("上传的文件不是图片");
        }
        String type = null;
        if (typeInteger == TYPE_TASK) {
            type = TASK;
        } else if (typeInteger == TYPE_AVATAR) {
            type = AVATAR;
        }

        String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                + "_" + type
                + "." + originalFilename.split("\\.")[1];
        String url = "";
        try (InputStream inputStream = file.getInputStream()) {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object("image" + "/" + type + "/" + fileName)
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object("image" + "/" + type + "/" + fileName)
                    .method(Method.GET)
                    .expiry(60)
                    .build());
        } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("Error occurred: ", e);
        }
        System.out.println("url:" + url);
        return url.split("\\?")[0];
    }

    public void setTmpTags(String avatarUrl) {
        // 创建标签映射
        Map<String, String> tags = new HashMap<>();
        tags.put("Temp", "true");

        // 为对象设置标签
        try {
            minioClient.setObjectTags(
                    SetObjectTagsArgs.builder()
                            .bucket(bucketName)
                            .object(avatarUrl.split(bucketName)[1])
                            .tags(tags)
                            .build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteTempTags(String avatarUrl) {
        try {
            // 删除对象的标签
            minioClient.deleteObjectTags(
                    DeleteObjectTagsArgs.builder()
                            .bucket(bucketName)
                            .object(avatarUrl.split(bucketName)[1])
                            .build());

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}